package util;

import java.awt.Color;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

import com.ltz.model.MonthlyProductData;

public class ExcelUtil {

	/**
	 * titleMap=[{'属性名1':'excel标题1'},{'属性名2':'excel标题2'}]
	 * data=包含对应属性的数据列表
	 * @param titleMap
	 * @param data
	 * @return
	 * @throws NoSuchFieldException 
	 * @throws SecurityException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 */
	public static HSSFWorkbook getBook(Map<String,String> titleMap,List data) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException{
		HSSFWorkbook workbook = new HSSFWorkbook();  
		//产生工作表对象  
		HSSFSheet sheet = workbook.createSheet();  
		HSSFRow row = sheet.createRow(0);//创建一行  
		HSSFCellStyle style=workbook.createCellStyle();
		HSSFFont font=workbook.createFont();
		font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
		style.setFillBackgroundColor(HSSFColor.GOLD.index);
		style.setFont(font);
		row.setRowStyle(style);
		Set<String> set=titleMap.keySet();
		Iterator<String> it=set.iterator();
		String s=null;
		int ci=0;
		while(it.hasNext()){
			s= it.next();
			HSSFCell cell = row.createCell(ci);//创建一列  
			sheet.setColumnWidth(ci, 20*256);
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);  
			cell.setCellValue(titleMap.get(s)); 
			ci++;
		}
		List l=null;
		Object obj=null;
		for (int i=0; i<data.size(); i++)  
		{  
			row = sheet.createRow(i+1);//创建一行  
			obj=data.get(i);
			ci=0;
			it=set.iterator();
			while(it.hasNext()){
				s= it.next();
				HSSFCell cell = row.createCell(ci);//创建一列  
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);  
				s=s.substring(0, 1).toUpperCase()+s.substring(1);
				cell.setCellValue(obj.getClass().getMethod("get"+s).invoke(obj)+""); 
				ci++;
			} 
		}  
		return workbook;
	}
}
